import socket, struct, sys, json, time

#if len(sys.argv) != 2:
#    print "python test.py query"
#    sys.exit(1)

def send_all(sock, log_id, jsonstr):
    sbuf = struct.pack(FMT_XHEAD, log_id, "selector", 0, 0, 0, len(jsonstr))
    sbuf += jsonstr
    ret = sock.send(sbuf)
    print "send %d bytes" % ret
    rbuf = sock.recv(36)
    print "recv %d bytes" % len(rbuf)
    log_id, srvname, headid, headversion, status, detail_len = struct.unpack(FMT_XHEAD, rbuf)
    print "log_id[%u] srvname[%s] status[%u] detail_len[%u]" % (log_id, srvname, status, detail_len)
    if detail_len > 0:
        rrbuf = sock.recv(detail_len)
        print struct.unpack("I"*(detail_len/4), rrbuf)
    else:
        print "detail_len = %d" % (detail_len,)

def send_piece(sock, log_id, jsonstr, piece_len):
    sbuf = struct.pack(FMT_XHEAD, log_id, "selector", 0, 0, 0, len(jsonstr))
    sbuf += jsonstr
    assert (len(sbuf) > 36)
    send_all = 0
    for x in xrange(1+(len(sbuf)/piece_len)):
        ret = sock.send(sbuf[x*piece_len:(x+1)*piece_len])
        print "ret: %02d send %d:%d bytes totle:%d bytes" % (ret, x*piece_len, (x+1)*piece_len, len(sbuf))
        send_all += ret
        time.sleep(1)
    print "send %d bytes, totle: %d bytes" % (send_all, len(sbuf))
    rbuf = sock.recv(36)
    print "recv %d bytes" % len(rbuf)
    log_id, srvname, headid, headversion, status, detail_len = struct.unpack(FMT_XHEAD, rbuf)
    print "log_id[%u] srvname[%s] status[%u] detail_len[%u]" % (log_id, srvname, status, detail_len)
    if detail_len > 0:
        rrbuf = sock.recv(detail_len)
        print struct.unpack("I"*(detail_len/4), rrbuf)
    else:
        print "detail_len = %d" % (detail_len,)


    

FMT_XHEAD = "I16sIIII"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 2006));

url_file = file(sys.argv[1])

dd = []
for line in url_file:
    dd.append(line.strip())
jsonstr = json.dumps(dd)
jsonstr = "aaaa"
for x in xrange(1):
    send_all(sock, x, jsonstr)
#piece_len = 17
#send_piece(sock, x, dd, piece_len)
